package work;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author admin
 * @Date 2019/4/12 10:13
 */
public class Test1 {
    public static void main(String[] args) {
        /*1.创建集合对象
         * 2.往集合对象中添加元素
         * 3.把集合中的数据写入文件
         * 1）遍历集合：
         *   1）取出集合中的一个元素
         *   2）用字符缓冲输出流写入文件（一次写一行文本）*/

        HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
        hashMap.put(1, "张一");
        hashMap.put(2, "张二");
        hashMap.put(3, "张三");
        hashMap.put(4, "张四");

        Writer out = null;
        BufferedWriter bw = null;
        try {
            out = new FileWriter("pan.txt");
            bw = new BufferedWriter(out);

            Set<Integer> set = hashMap.keySet();
            Iterator iterator = set.iterator();

            while (iterator.hasNext()) {
                Integer key = (Integer) iterator.next();
                String value = hashMap.get(key);
                bw.write(key + "-" + value);
                bw.newLine();
            }
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
